from tkinter import *
from tkinter import messagebox
from weibo_utils import get_weibo_posts, save_to_excel
from tkinter import ttk

global username_entry, year_var, month_var


def fetch_and_save():
    username = username_entry.get()
    year = year_var.get()
    month = month_var.get()

    try:
        posts = get_weibo_posts(username, year, month)
        save_to_excel(posts, username, year, month)
        messagebox.showinfo("成功", "推文已保存到文件中。")
    except Exception as e:
        messagebox.showerror("错误", f"发生错误：{str(e)}")


def create_ui():
    root = Tk()
    root.title("微博推文获取工具")

    # 设置窗口大小
    root.geometry("400x200")

    frame = Frame(root)
    frame.pack(padx=10, pady=10)
    Label(frame, text="微博用户昵称：").grid(row=0, column=0, sticky="e")
    username_entry = Entry(frame)
    username_entry.grid(row=0, column=1, pady=5)
    username_entry.insert(0, "HTCVIVE虚拟现实")

    Label(frame, text="年份：").grid(row=1, column=0, sticky="e")
    year_var = StringVar()
    year_combo = ttk.Combobox(frame, textvariable=year_var, state="readonly")
    year_combo["values"] = list(range(2009, 2031))  # 从2000年到2030年
    year_combo.set("2024")  # 设置默认值为2024年
    year_combo.grid(row=1, column=1, pady=5)

    Label(frame, text="月份：").grid(row=2, column=0, sticky="e")
    month_var = StringVar()
    month_combo = ttk.Combobox(frame, textvariable=month_var, state="readonly")
    month_combo["values"] = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]
    month_combo.set("04")  # 设置默认值为4月
    month_combo.grid(row=2, column=1, pady=5)

    fetch_button = Button(frame, text="获取并保存", command=fetch_and_save)
    fetch_button.grid(row=3, columnspan=2)

    root.mainloop()
